package tpase.KeyServer.DAO;

import tpase.KeyServer.DO.KeyShare;
import tpase.KeyServer.VO.SecretKey;
import tpase.util.JDBCUtil;

import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class KeyShareDao {
    private String configPath;
    public KeyShareDao(String configPath) {
        this.configPath = configPath;
    }
    public void clearKeyShare() {
        Connection connection = JDBCUtil.getConnect(configPath);
        String sql = "DELETE FROM key_share";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareCall(sql);
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement);
        }
    }

    public void storeKeyShare(KeyShare keyShare) {
        Connection connection = JDBCUtil.getConnect(configPath);
        String sql = "INSERT INTO key_share (key_server_id, si) VALUES (?, ?)";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, keyShare.getKeyServerId());
            statement.setBinaryStream(2, new ByteArrayInputStream(keyShare.getSi()));
            statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement);
        }
    }

    public KeyShare getKeyShare() {
        Connection connection = JDBCUtil.getConnect(configPath);
        String sql = "SELECT key_server_id, si FROM key_share";
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        KeyShare keyShare = null;
        try {
            statement = connection.prepareCall(sql);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                keyShare = new KeyShare(resultSet.getString("key_server_id"), resultSet.getBytes("si"));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JDBCUtil.close(connection, statement, resultSet);
        }
        if (keyShare == null) {
            throw new RuntimeException("getKeyShare, 查询 KeyShare 不存在");
        }
        return keyShare;
    }

    public static void main(String[] args) {
        KeyShareDao keyShareDao = new KeyShareDao("config/server0/config.properties");
        keyShareDao.clearKeyShare();
        byte[] bytes = {1, 2};
        keyShareDao.storeKeyShare(new KeyShare("11", bytes));
        KeyShare keyShare = keyShareDao.getKeyShare();
        System.out.println(keyShare.getKeyServerId());
        for (byte b : keyShare.getSi()) {
            System.out.println(b);
        }
    }
}
